package com.roger.springcloudGreenwich.dao;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.roger.springcloudGreenwich.bean.Student;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2020/3/25.
 */
@Repository
@Slf4j
public class StudentDao {
    @Autowired
    private TransportClient transportClient;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 功能描述：批量导入文档
     *
     * @param index
     *            索引名
     * @param type
     *            索引类型
     * @param objects
     *            文档内容
     */
    public void bulkCreate(String index, String type, List<Student> objects) throws Exception{
        BulkRequest bulkRequest = new BulkRequest();
        IndexRequest indexRequest;
        ObjectMapper mapper = new ObjectMapper();
        try {
            for (Student o : objects) {
                indexRequest = new IndexRequest(index, type, o.getId());
                indexRequest.source(mapper.writeValueAsString(o), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            transportClient.bulk(bulkRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //这里为什么不能close?
            //if(transportClient != null)
                //transportClient.close();
        }
    }


    public void highLevelBulkCreate(String index, String type, List<Student> objects) throws Exception{
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest("index", "type", "1")
                .source(XContentType.JSON, "field", "foo"));
        request.add(new IndexRequest("index", "type", "2")
                .source(XContentType.JSON, "field", "bar"));
        request.add(new IndexRequest("index", "type", "3")
                .source(XContentType.JSON, "field", "baz"));

//同步
        restHighLevelClient.bulk(request);

    }


}
